package com.cristina.attention.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cristina.attention.entity.Friend;
import com.cristina.attention.entity.User;
import com.cristina.attention.entity.vo.AddFriendVo;
import com.cristina.attention.exception.BadRequestException;
import com.cristina.attention.mapper.FriendMapper;
import com.cristina.attention.mp.base.BaseServiceImpl;
import com.cristina.attention.utils.AttentionCommon;
import com.cristina.attention.utils.StringUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author superman
 * @Date 2021/11/13 18:52
 **/
@Service
@Slf4j
@AllArgsConstructor
public class FriendServiceImpl extends BaseServiceImpl<FriendMapper, Friend> implements FriendService {

    private final UserService userService;

    @Override
    public List<User> findFriendBelonging(Long originId) {
        // select * from im_friend where origin_id = originId or target_id = originId
        List<Friend> friends = this.list(Wrappers.lambdaQuery(Friend.class).eq(Friend::getOriginId, originId).or().eq(Friend::getTargetId, originId));
        if (friends.size() < 1) {
            return new ArrayList<>();
        }
        // select * from im_user where user_id in ('')
        Set<Long> targetIds = friends.stream().flatMap(map -> Stream.of(map.getOriginId(), map.getTargetId())).collect(Collectors.toSet());
        return userService.list(Wrappers.lambdaQuery(User.class).in(User::getUserId, targetIds));
    }

    @Override
    public boolean addFriend(AddFriendVo addFriendVo) {
        if (StringUtils.isEmpty(addFriendVo.getTargetId())) {
            throw new BadRequestException("添加好友的id为空");
        }
        User user;
        try {
            user = userService.getOne(
                    Wrappers.lambdaQuery(User.class).and(i -> i
                            .like(User::getUsername, addFriendVo.getTargetId())
                            .or()
                            .like(User::getImId, addFriendVo.getTargetId())),
                    AttentionCommon.TRUE
            );
        } catch (Exception e) {
            throw new BadRequestException("添加的好友有多个");
        }
        if (Objects.isNull(user)) {
            throw new BadRequestException("好友不存在");
        }
        Friend friend = new Friend();
        friend.setOriginId(addFriendVo.getOriginId());
        friend.setTargetId(user.getUserId());
        friend.setApplyTime(System.currentTimeMillis());
        return this.save(friend);
    }
}
